<template>
  <div class="upload-form">
    <label for="file-input" class="file-label">
      <span v-if="selectedFile" >换一个</span>
      <span v-else>选择头像</span>
    </label>
    <input id="file-input" type="file" @change="handleFileChange" accept="image/*" class="file-input">
    <div v-if="selectedFile || imagePreviewUrl" class="image-preview" :style="{ backgroundImage: 'url(' + imagePreviewUrl + ')' }">
      <img :src="imagePreviewUrl || defaultImage" alt="Preview" class="preview-image">
    </div>
    <label for="file-input" class="custom-file-upload" style="width: 45%;text-align: center;">选择文件</label>
    <button @click="upload" class="upload-button"  style="width: 50%;text-align: center">上传头像</button>
    <p v-if="fileSizeError" class="error-message">{{ fileSizeError }}</p>
  </div>
</template>

<style>
.upload-form {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.file-label {
  display: none;
}

.custom-file-upload {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-bottom: 10px;
  display: inline-block;
}

.file-input {
  display: none;
}

.image-preview {
  width: 400px;
  height: 300px;
  background-size: cover;
  background-position: center;
  margin-top: 10px;
  border-radius: 5px;
  overflow: hidden;
  position: relative;
}

.preview-image {
  visibility: hidden;
}

.upload-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.upload-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.upload-button:hover {
  background-color: #0056b3;
}

.error-message {
  color: red;
  margin-top: 10px;
}
.custom-file-upload {
  padding: 10px 20px;
  background-color: #4CAF50; /* Green background color */
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-bottom: 10px;
  display: inline-block;
  transition: background-color 0.3s; /* Add smooth transition */
}

.custom-file-upload:hover {
  background-color: #45a049; /* Darker green color on hover */
}
</style>

<script>
import axios from 'axios';
import defaultImage from "../assets/01.jpg";
import {ElNotification} from "element-plus";
import {h, ref} from "vue";
import router from "@/utils/router.js";
const fullscreenLoading = ref(false)
export default {
  data() {
    return {
      selectedFile: null,
      imagePreviewUrl: '',
      defaultImage: defaultImage,
      fileSizeError: ''
    };
  },
  methods: {
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file.size < 1024 || file.size > 5 * 1024 * 1024) {
        this.fileSizeError = '文件大小必须在1KB到5MB之间';
        this.selectedFile = null;
        this.imagePreviewUrl = '';
      } else {
        this.selectedFile = file;
        this.imagePreview();
        this.fileSizeError = '';
      }
    },
    imagePreview() {
      if (!this.selectedFile) {
        this.imagePreviewUrl = '';
        return;
      }
      const reader = new FileReader();
      reader.onload = (e) => {
        this.imagePreviewUrl = e.target.result;
      };
      reader.readAsDataURL(this.selectedFile);
    },
    async upload() {
      const formData = new FormData();
      formData.append('file', this.selectedFile);

      try {
        const response = await axios.patch('/user/updateAvatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(result=>{
          if (result.data.code==0){
            router.push("/user/userinfo")
            return   ElNotification({
              title: '消息',
              message: h('i', { style: 'color: teal' },'头像上传成功'),
            })

          }else {
            return   ElNotification({
              title: '消息',
              message: h('i', { style: 'color: teal' },'头像上传失败'),
            })
          }
        })


      } catch (error) {

        return   ElNotification({
          title: '消息',
          message: h('i', { style: 'color: teal' },'头像上传失败'),
        })
      }
    }
  }
};
</script>
